import { MenuService } from './../../../@core/services/menu/menu.service';
import { SharedMethodService } from './../../../@core/services/Sharedmethod/shared-method.service';
import { Component, ViewChild, ViewChildren } from '@angular/core';
import { DataTableComponent, DialogService, TableWidthConfig } from 'ng-devui';
import { AddRoleComponent } from './add-role/add-role.component';
import { EditRoleComponent } from './edit-role/edit-role.component';
import { RoleService } from 'src/app/@core/services/role/role.service';
import { PermissionsComponent } from './permissions/permissions.component';
import { Subject, takeUntil } from 'rxjs';
import menu from '../../menu';
import { TranslateService, TranslationChangeEvent } from '@ngx-translate/core';
import { MobilePermissionsComponent } from './mobile-permissions/mobile-permissions.component';

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.scss']
})
export class RoleComponent {
  roleData:any[]=[]
  allCheckedStatus = false;
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  checkedIds = [];
  pageSizeOptions = [10, 20, 30, 50, 100];
  msgs: { severity: any; summary: any; content: any; }[];
  config = {
    id: 'Add-role',
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  filterRole:string = '';
  TreeData:any = [];
  allChecked: boolean = false;
  @ViewChild(DataTableComponent, { static: true }) datatable: DataTableComponent;
  constructor( private roleservice:RoleService,private dialogService: DialogService,private translate:TranslateService,private SharedMethodService:SharedMethodService,private MenuService:MenuService){}
  ngOnInit(): void {
   this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize,null).subscribe((data:any)=>{
     this.roleData=data.items
     this.pager.total=data.totalCount;
   })
   this.translate
      .get('page')
      .pipe(takeUntil(this.destroy$))
      .subscribe((res) => {
        this.updateMenu(res);
      });
   this.translate.onLangChange.pipe(takeUntil(this.destroy$)).subscribe((event: TranslationChangeEvent) => {
    const values = this.translate.instant('page');
    this.updateMenu(values);
  });
  }
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '角色名称',
        fieldType: 'text'
      },
      {
        field: 'isEmpowerment',
        header: '状态',
        fieldType: 'boolean'
      }
    ]
  };//表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field:'name',
      width:'150px'
    },
    {
      field: 'isEmpowerment',
      width: '250px'
    },
    {
      field: '操作',
      width: '350px'
    }
  ];//表格宽度配置

  pageIndexChange($event: any) {
    this.pager.pageIndex=$event;
    this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.roleData=data.items;
    })//获取编码规则
  }//切换页码
  pageSizeChange($event: any){
    this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.roleData=data.items;
    })//获取编码规则
  }//改变每页显示数量
  DeleteRole(rowitem:any,dialogtype?:string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除角色',
      content: '确认删除该角色？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.roleservice.DeleteRoles([rowitem.id]).subscribe((data:any)=>{
              results.modalInstance.hide();
              this.showToast('success','成功','角色删除成功')
              this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                this.roleData=data.items;
                this.pager.total=data.totalCount;
              })//获取编码规则
            },
            (error) => {
              if(error.status==404){
                this.showToast('error', '失败', '服务器连接失败');
              }else{
                this.showToast('error', '失败', error.error);
              }
            }
            )
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }//删除
  CheckDeleteRole(dialogtype?:string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除角色',
      content: '确认删除该角色？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {

              this.roleservice.DeleteRoles(this.checkedIds).subscribe(
                data=>{
                  results.modalInstance.hide();
                  this.showToast('success','成功','角色删除成功')
                  this.checkedIds = []
                  this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                    this.roleData=data.items;
                    this.pager.total=data.totalCount;
                  })//获取编码规则
                },(error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                }
              )
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }//删除
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  CreatRole(dialogtype?:string){
    let data = {
      display: false,
    };
    const results = this.dialogService.open({
      ...this.config,
      data:data,
      title: '添加角色',
      content: AddRoleComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.PostRole.name){
              this.roleservice.CreateRole(results.modalContentInstance.PostRole).subscribe((data:any)=>{
                results.modalInstance.hide();
                this.showToast('success','成功','角色添加成功')
                this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.roleData=data.items;

                  this.pager.total=data.totalCount;
                })//获取编码规则
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
                results.modalInstance.hide();
              })
            }
              data.display = true

          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }//创建角色
  EditRole(rowItem:any,dialogtype?:string){
    let data = {
      rowItem:rowItem,
      display: false,
    };
    const results = this.dialogService.open({
      ...this.config,
      data:data,
      title: '更新角色',
      content: EditRoleComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.PutRole.name){
              this.roleservice.UpdateRole(rowItem.id, results.modalContentInstance.PutRole).subscribe((data:any)=>{
                results.modalInstance.hide();
                this.showToast('success','成功','角色更新成功')
                this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.roleData=data.items;

                  this.pager.total=data.totalCount;
                })//获取编码规则
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
                results.modalInstance.hide();
              })
            }
              data.display = true

          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });

  }//创建角色
  filter(){
    this.roleservice.fifterRoles(this.pager.pageIndex,this.pager.pageSize,this.filterRole).subscribe((data:any)=>{
      this.roleData=data.items;
      this.pager.total=data.totalCount;
    })
  }//搜索
  reset(){
    this.filterRole='';
    this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.roleData=data.items;
      this.pager.total=data.totalCount;
    })
  }
  Permissions(rowItem:any,dialogtype?:string){
    let data = {
      rowItem:rowItem,
      display: false,
    };
    const results = this.dialogService.open({
      ...this.config,
      maxHeight: '700px',
      width: '700px',
      data:data,
      title: '后台权限',
      content: PermissionsComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '更新权限',
          handler: ($event: Event) => {
            this.MenuService.UpdateRoleMenus(rowItem.id,results.modalContentInstance.selectMenus).subscribe((data:any)=>{
              this.showToast('success','成功','权限更新成功')
              results.modalInstance.hide();
            },(error) => {
              if(error.status==404){
                this.showToast('error', '失败', '服务器连接失败');
              }else{
                this.showToast('error', '失败', error.error);
              }
            }
          )
          },
        },
        {
          id: 'btn-all',
          cssClass: 'primary',
          text: '全选',
          handler: ($event: Event) => {
            results.modalContentInstance.displayData = this.checkAllNodes(results.modalContentInstance.displayData);
            results.modalContentInstance.selectTitle=this.getTitles(results.modalContentInstance.displayData);
            results.modalContentInstance.selectMenus=results.modalContentInstance.displayData;
          },
        },
        {
          id: 'btn-all',
          cssClass: 'primary',
          text: '清空',
          handler: ($event: Event) => {
            results.modalContentInstance.displayData = this.removeChecked(results.modalContentInstance.displayData);
            results.modalContentInstance.selectMenus=[];
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//后台权限
  Mpermissions(rowItem:any,dialogtype?:string){
    let data = {
      rowItem:rowItem,
      display: false,
    };
    const results = this.dialogService.open({
      ...this.config,
      maxHeight: '700px',
      width: '700px',
      data:data,
      title: '移动端权限',
      content: MobilePermissionsComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '更新权限',
          handler: ($event: Event) => {
            this.MenuService.UpdateAppRoleMenus(rowItem.id,results.modalContentInstance.selectMenus).subscribe((data:any)=>{
              this.showToast('success','成功','权限更新成功')
              results.modalInstance.hide();
            },(error) => {
              if(error.status==404){
                this.showToast('error', '失败', '服务器连接失败');
              }else{
                this.showToast('error', '失败', error.error);
              }
            }
          )
          },
        },
        {
          id: 'btn-all',
          cssClass: 'primary',
          text: '全选',
          handler: ($event: Event) => {
            results.modalContentInstance.displayData = this.checkAllNodes(results.modalContentInstance.displayData);
            results.modalContentInstance.selectTitle=this.getTitles(results.modalContentInstance.displayData);
            results.modalContentInstance.selectMenus=results.modalContentInstance.displayData;
          },
        },
        {
          id: 'btn-all',
          cssClass: 'primary',
          text: '清空',
          handler: ($event: Event) => {
            results.modalContentInstance.displayData = this.removeChecked(results.modalContentInstance.displayData);
            results.modalContentInstance.selectMenus=[];
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//后台权限
  private destroy$ = new Subject<void>();
  updateMenu(values: any) {
    this.TreeData = menu(values);
  }
  checkAllNodes(nodes: any[]) {
    return nodes.map((node: { childrenMenu: any; }) => {
      let newNode = { ...node, isChecked: true };
      if (node.childrenMenu) {
        newNode.childrenMenu = this.checkAllNodes(node.childrenMenu);
      }
      return newNode;
    });
  }
  removeChecked(nodes: any[]) {
    return nodes.map((node: { childrenMenu: any; isChecked?: boolean }) => {
      let { isChecked, ...newNode } = node;
      if (node.childrenMenu) {
        newNode.childrenMenu = this.removeChecked(node.childrenMenu);
      }
      return newNode;
    });
  }//移除选中
  getTitles(nodes: any[]) {
    let titles = [];
    nodes.forEach(node => {
      if (node && node.title) {
        titles.push(node.title);
      }
      if (node && node.childrenMenu) {
        titles = titles.concat(this.getTitles(node.childrenMenu));
      }
    });
    return titles;
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }){
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable)
  }
  getCheckedRows() {
    this.roleData.forEach(row => {
      if (row.name == '超级管理员') {
        row.$checked = false;
      }
    });
    this.SharedMethodService.getCheckedRows(this.datatable,'id').subscribe((data:any)=>{
      this.checkedIds=data;
    })
    console.log(this.checkedIds)
  }//获取选中行
  cleared(){
    this.SharedMethodService.cleared(this.checkedIds,this.roleData,this.datatable).subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }//清空选中行
  enable(){
    this.roleservice.EnableRoles(this.checkedIds).subscribe((data:any)=>{
      this.showToast('success','成功','启用成功')
      this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.roleData=data.items;
        this.pager.total=data.totalCount;
        this.checkedIds=[];
      })//
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//启用
  disable(){
    this.roleservice.DisableRoles(this.checkedIds).subscribe((data:any)=>{
      this.showToast('success','成功','禁用成功')
      this.roleservice.getAllRoles(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.roleData=data.items;
        this.pager.total=data.totalCount;
        this.checkedIds=[];

      })//
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//禁用
}
